#!/bin/bash
# -*- Mode: sh; indent-tabs-mode: nil; tab-width: 4 -*-

#
# Copyright (C) 2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Our goal here is to get an Ubuntu Touch device into a testable unlocked state.
# This will include a reboot.

WAIT_COMMAND="adb reboot; sleep 5; adb wait-for-device; sleep 20"

while getopts s:w: opt; do
        case $opt in
        s)
                export ANDROID_SERIAL=$OPTARG
                ;;
        w)
                WAIT_COMMAND=$OPTARG
                ;;
        esac
done

eval "$WAIT_COMMAND"

for i in `seq 1 5`; do
    # We need to go through sudo to get a proper environment for dbus set up
    UNLOCK_OUTPUT=$(adb shell "gdbus call --session --dest com.canonical.UnityGreeter --object-path / --method com.canonical.UnityGreeter.HideGreeter && echo Greeter unlocked" 2>&1)
    if echo "$UNLOCK_OUTPUT" | grep 'Greeter unlocked' >/dev/null; then
        echo "I: Unlock passed"
        exit 0
    else
        echo "I: Unlock attempt $i failed, script output: '$UNLOCK_OUTPUT'"
        sleep 20
    fi
done

echo "I: Too many unlock failures, giving up"
exit 1
